<template>
  <PageCard title="curl 工具集">
    <n-spin :show="loading">
      <n-space vertical size="large">
          <!-- 域名替换功能 -->
          <n-card title="域名替换" hoverable>
            <n-space vertical>
              <n-input
                v-model:value="replaceDomainForm.curlCommand"
                type="textarea"
                :rows="4"
                placeholder="请输入 curl 命令"
                clearable
              />
              <n-input
                v-model:value="replaceDomainForm.newDomain"
                placeholder="请输入新域名 (例如: https://new-domain.com)"
                clearable
              >
                <template #suffix v-if="domainHistory.length > 0">
                  <n-dropdown
                    :options="domainHistory.map(domain => ({ 
                      label: domain, 
                      key: domain,
                      props: {
                        onClick: () => selectHistoryDomain(domain)
                      }
                    }))"
                    trigger="click"
                  >
                    <n-button text>
                      <template #icon>
                        <n-icon>
                          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
                            <path d="M7 10l5 5 5-5z"/>
                          </svg>
                        </n-icon>
                      </template>
                    </n-button>
                  </n-dropdown>
                </template>
              </n-input>
              <n-button 
                type="primary" 
                @click="handleReplaceDomain" 
                :loading="replaceLoading"
                :disabled="!replaceDomainForm.curlCommand || !replaceDomainForm.newDomain"
              >
                替换域名
              </n-button>
            </n-space>
            
            <div v-if="replaceResult" class="mt-4">
              <n-divider />
              <n-space vertical>
                <n-text strong>替换结果：</n-text>
                <n-text type="info">原始域名：{{ replaceResult.originalDomain }}</n-text>
                <n-text type="success">新域名：{{ replaceResult.newDomain }}</n-text>
                <n-input
                  :value="replaceResult.newCurl"
                  type="textarea"
                  :rows="4"
                  readonly
                />
                <n-button 
                  secondary 
                  @click="copyToClipboard(replaceResult.newCurl)"
                >
                  复制新 curl 命令
                </n-button>
              </n-space>
            </div>
          </n-card>

          <!-- curl 执行功能 -->
          <n-card title="curl 命令执行" hoverable>
            <n-space vertical>
              <n-input
                v-model:value="executeForm.curlCommand"
                type="textarea"
                :rows="4"
                placeholder="请输入要执行的 curl 命令"
                clearable
              />
              <n-input-number
                v-model:value="executeForm.timeoutMs"
                :min="1000"
                :max="120000"
                :step="1000"
                placeholder="超时时间（毫秒）"
                class="w-[200px]"
              >
                <template #suffix>ms</template>
              </n-input-number>
              <n-button 
                type="primary" 
                @click="handleExecuteCurl" 
                :loading="executeLoading"
                :disabled="!executeForm.curlCommand"
              >
                执行 curl 命令
              </n-button>
            </n-space>

            <div v-if="executeResult" class="mt-4">
              <n-divider />
              <n-space vertical>
                <n-space>
                  <n-text strong>执行结果：</n-text>
                  <n-tag :type="executeResult.success ? 'success' : 'error'">
                    {{ executeResult.success ? '成功' : '失败' }}
                  </n-tag>
                  <n-text type="info">耗时：{{ executeResult.executionTimeMs }}ms</n-text>
                </n-space>
                
                <div v-if="executeResult.errorMessage">
                  <n-text type="error">错误信息：{{ executeResult.errorMessage }}</n-text>
                </div>
                
                <div>
                  <n-text strong>响应内容：</n-text>
                  <n-input
                    :value="executeResult.response"
                    type="textarea"
                    :rows="8"
                    readonly
                  />
                  <div class="mt-2">
                    <n-button 
                      secondary 
                      @click="copyToClipboard(executeResult.response)"
                    >
                      复制响应内容
                    </n-button>
                    <n-button 
                      secondary 
                      @click="formatJson"
                      class="ml-2"
                    >
                      格式化 JSON
                    </n-button>
                  </div>
                </div>
              </n-space>
            </div>
          </n-card>

        </n-space>
    </n-spin>
    
    <n-divider />
    
    <UsageGuide
      :title="usageGuideConfig.title"
      :steps="usageGuideConfig.steps"
      :tips="usageGuideConfig.tips"
      :example="usageGuideConfig.example"
    />
  </PageCard>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useMessage } from 'naive-ui';
import PageCard from "@/components/PageCard.vue";
import UsageGuide from "@/components/UsageGuide.vue";
import { 
  replaceCurlDomain, 
  executeCurlCommand, 
  type ReplaceDomainRequest, 
  type ExecuteCurlRequest, 
  type ReplaceDomainResponse, 
  type ExecuteCurlResponse 
} from "@/api/curl/index.ts";

const message = useMessage();
const loading = ref(false);
const replaceLoading = ref(false);
const executeLoading = ref(false);

// 域名替换表单
const replaceDomainForm = reactive<ReplaceDomainRequest>({
  curlCommand: '',
  newDomain: ''
});

// curl 执行表单
const executeForm = reactive<ExecuteCurlRequest>({
  curlCommand: '',
  timeoutMs: 30000
});

// 结果数据
const replaceResult = ref<ReplaceDomainResponse | null>(null);
const executeResult = ref<ExecuteCurlResponse | null>(null);

// 本地存储键名
const STORAGE_KEY = 'curl-tools-domains';

// UsageGuide configuration
const usageGuideConfig = {
  title: '使用说明',
  steps: [
    '域名替换：输入完整的curl命令和新域名，系统会自动识别并替换',
    'curl执行：输入要执行的curl命令，设置超时时间，点击执行',
    '查看结果：执行完成后可查看响应内容、耗时等信息',
    '格式化JSON：如果响应是JSON格式，可以点击格式化按钮美化显示'
  ],
  tips: [
    '域名历史：系统会自动保存最近使用的10个域名，方便快速选择',
    '自动复制：域名替换成功后会自动复制新命令到剪贴板',
    '超时设置：默认30秒，可根据需要调整（1-120秒）',
    '安全提示：执行功能会实际发送请求，请谨慎使用，避免执行可能造成安全风险的命令'
  ],
  example: 'curl \'https://api.example.com/users\' -H \'Accept: application/json\' 替换为 https://api-test.example.com'
};

// 从本地存储加载域名历史
const loadDomainHistory = (): string[] => {
  try {
    const stored = localStorage.getItem(STORAGE_KEY);
    return stored ? JSON.parse(stored) : [];
  } catch (error) {
    console.error('加载域名历史失败:', error);
    return [];
  }
};

// 保存域名到本地存储
const saveDomainToHistory = (domain: string) => {
  try {
    const history = loadDomainHistory();
    // 去重并添加到首位
    const newHistory = [domain, ...history.filter(d => d !== domain)].slice(0, 10); // 最多保存10个
    localStorage.setItem(STORAGE_KEY, JSON.stringify(newHistory));
  } catch (error) {
    console.error('保存域名历史失败:', error);
  }
};

// 域名历史列表
const domainHistory = ref<string[]>([]);

// 域名替换处理
const handleReplaceDomain = async () => {
  replaceLoading.value = true;
  replaceResult.value = null;
  
  try {
    const response: any = await replaceCurlDomain(replaceDomainForm);
    replaceResult.value = response.data;
    
    // 保存新域名到本地存储
    saveDomainToHistory(replaceDomainForm.newDomain);
    domainHistory.value = loadDomainHistory();
    
    // 自动复制新的 curl 命令
    await copyToClipboard(response.data.newCurl);
    message.success('域名替换成功，新命令已复制到剪贴板');
  } catch (error) {
    console.error('域名替换失败:', error);
    message.error('域名替换失败');
  } finally {
    replaceLoading.value = false;
  }
};

// curl 执行处理
const handleExecuteCurl = async () => {
  executeLoading.value = true;
  executeResult.value = null;
  
  try {
    const response: any = await executeCurlCommand(executeForm);
    executeResult.value = response.data;
    message.success('curl 命令执行完成');
  } catch (error) {
    console.error('curl 执行失败:', error);
    message.error('curl 执行失败');
  } finally {
    executeLoading.value = false;
  }
};

// 复制到剪贴板
const copyToClipboard = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text);
    message.success('已复制到剪贴板');
  } catch (error) {
    console.error('复制失败:', error);
    message.error('复制失败');
  }
};

// 格式化 JSON
const formatJson = () => {
  if (!executeResult.value?.response) return;
  
  try {
    const parsed = JSON.parse(executeResult.value.response);
    executeResult.value.response = JSON.stringify(parsed, null, 2);
    message.success('JSON 格式化成功');
  } catch (error) {
    message.warning('响应内容不是有效的 JSON 格式');
  }
};

// 选择历史域名
const selectHistoryDomain = (domain: string) => {
  replaceDomainForm.newDomain = domain;
};

// 组件挂载时加载域名历史和上次使用的域名
onMounted(() => {
  domainHistory.value = loadDomainHistory();
  // 如果有历史记录，自动填入最近使用的域名
  if (domainHistory.value.length > 0) {
    replaceDomainForm.newDomain = domainHistory.value[0];
  }
});
</script>

<style scoped>
:deep(.n-card) {
  @apply mb-4;
}

:deep(.n-input) {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
}

:deep(.n-input--textarea .n-input__textarea) {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
}
</style>